<?php

class FightAction extends CAction
{
	const FIGHT_INTERVAL_TIME=0;
    const AUTO_FIGHT_INTERVAL_TIME = 1000;
	const INVALID_FIGHT_EXPIRE_TIME=3;

	private $_fight;

	private function startFight()
	{
		$locationId=$this->controller->getUserLocationId();
		$location=Location::loadLocation($locationId);

		if(!$location->fightable)
			throw new CHttpException(401,'cannot fight in location['.$locationId.'] for user['.Yii::app()->user->name.']');

		$pet=$this->controller->getActivePet();
		if(!$pet)
			throw new CHttpException(500, 'canont find active pet for user['.Yii::app()->user->name.']');

		$this->_fight=new Fight($pet, $location->createEnemy(), $locationId);
        $this->controller->render('fight/StartFight', 
            array(
                'self'=>$this->_fight->self,
                'enemy'=>$this->_fight->enemy,
                'locationId'=>$this->controller->getUserLocationId(),
                'delayTime'=>self::AUTO_FIGHT_INTERVAL_TIME,
            )
        );
	}

	private function waitForFight($time)
	{
		echo "you have to wait for $time to start a new fight";
	}

	private function fightTooFrequently($time)
	{
		echo "fight too frequently, wait for $time";
	}

    private function fight()
    {
        $result = $this->_fight->fightRound();
        if ( $this->_fight->finished() ) {
            $this->_fight->valid=false;
        }
        
        $this->controller->render('fight/Fighting', 
            array(
                'result'=>print_r($result, true),
                'delayTime'=>self::AUTO_FIGHT_INTERVAL_TIME,
            )
        );        
    }
    
	public function run()
	{
		$this->_fight=Fight::loadFight();

		if($this->_fight===null)
			$this->startFight();
		else {
			if(!$this->_fight->valid) {
				$waitTime=self::INVALID_FIGHT_EXPIRE_TIME + $this->_fight->lastRoundTime - time();
				if($waitTime<=0)
					$this->startFight();
				else
					$this->waitForFight($waitTime);	
			}
			else {
				$intervalTime=time() - $this->_fight->lastRoundTime;
				if($intervalTime<self::FIGHT_INTERVAL_TIME)
					$this->fightTooFrequently(self::FIGHT_INTERVAL_TIME-$intervalTime);
				else
					$this->fight();
			}
		}

		Fight::saveFight($this->_fight);
	}
}

?>
